#include "Canvas.h"
#include"Space.h"
#include"agk.h"

int Canvas::width = 1;
int Canvas::height = 1;
Color** Canvas::colorBuffer = nullptr;
double** Canvas::depthBuffer = nullptr;
bool Canvas::isDoubleBuffer = false;

Canvas::Canvas()
{
}


Canvas::~Canvas()
{
}

void Canvas::Init(int width, int height)
{
	Canvas::width = width;
	Canvas::height = height;
	isDoubleBuffer = true;
	depthBuffer = Space::Create<double>(width, height);
	colorBuffer = Space::Create<Color>(width, height);
	Clear();
}

void Canvas::Destroy()
{
	Space::Delete(depthBuffer, width);
	Space::Delete(colorBuffer, width);
}

void Canvas::Clear(Color color)
{
	Space::Set(colorBuffer, width, height, color);
	Space::Set(depthBuffer, width, height, -1e10);
}

void Canvas::Show()
{
	for (int i = 0; i < width; i++)
	{
		for (int j = 0; j < height; j++)
		{
			int c = colorBuffer[i][j].GetValue();
			agk::DrawLine(i, j, i, j, c, c);
		}
	}
}

void Canvas::AntiAliasing()
{
	int r = 1;
	for (int i = r; i < width-r; i++)
	{
		for (int j = r; j < height - r; j++)
		{
			Color c[9];
			c[0] = colorBuffer[i - 1][j - 1];
			c[1] = colorBuffer[i][j - 1];
			c[2] = colorBuffer[i + 1][j - 1];
			c[3] = colorBuffer[i - 1][j];
			c[4] = colorBuffer[i][j];
			c[5] = colorBuffer[i + 1][j];
			c[6] = colorBuffer[i - 1][j + 1];
			c[7] = colorBuffer[i][j + 1];
			c[8] = colorBuffer[i + 1][j + 1];
			Color ec;
			for (int i = 0; i < 9; i++)
			{
				ec += c[i] / 9;
			}
			colorBuffer[i][j] = ec;
		}
	}
}

void Canvas::SetPixel(int x, int y, Color c)
{
	int i = x + width / 2;
	int j = height / 2 - y;
	if (i >= 0 && i < width && j >= 0 && j < height)
		colorBuffer[i][j] = c;
	if (!isDoubleBuffer)
	{
		Show();	
		agk::Sync();
	}
}

void Canvas::SetPixel(int x, int y, Color c, double depth)
{
	int i = x + width / 2;
	int j = height / 2 - y;
	if (i >= 0 && i < width && j >= 0 && j < height)
	{
		if (depth > depthBuffer[i][j])
		{
			depthBuffer[i][j] = depth;
			colorBuffer[i][j] = c;

			if (!isDoubleBuffer)
			{
				Show();
				agk::Sync();
			}
		}
	}	
}

void Canvas::SetPixel(int x, int y, double depth)
{
	int i = x + width / 2;
	int j = height / 2 - y;
	if (i >= 0 && i < width && j >= 0 && j < height)
	{
		if (depth > depthBuffer[i][j])
		{
			depthBuffer[i][j] = depth;
		}
	}
}


